package cn.kgc.dao;

import cn.kgc.entity.Usr;
import cn.kgc.utils.JDBCUtil;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author mosin
 * date 2022/2/11
 * @version 1.0
 * 用户数据的持久化层   数据库相关操作
 */
public class UserDaoImpl implements  UserDao {

    //用户的登陆
    public Usr login(Usr usr){

        Connection connection = JDBCUtil.getConnection();
        ResultSet resultSet = null;
        Statement stmt = null;
        try {
            stmt = connection.createStatement();
            String sql = "select username,password from usr where username= '"+usr.getUsername()+"' and password = '"+usr.getPassword()+"' ";
            System.out.println("sql = " + sql);
            resultSet = stmt.executeQuery(sql);
            //处理结果集
            Usr user = null;
            while (resultSet.next()){
                String uname = resultSet.getString(1);
                String pwd = resultSet.getString(2);
                user = Usr.builder().username(uname).password(pwd).build();
            }
            return  user;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {//释放资源
            JDBCUtil.closeAll(resultSet,stmt,connection);
        }

        return null;
    }


    //用户的注册
    public  int register(Usr usr){

        //使用jdbc进行数据的持久化操作   usr
        Connection connection = JDBCUtil.getConnection();
        Statement stmt = null;
        try {
            //获取操作数据库的对象 stmt
            stmt = connection.createStatement();
            Date createTime = usr.getCreateTime();
            Date birth = usr.getBirth();

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String StrCreateTime = simpleDateFormat.format(createTime);
            String StrBirth = simpleDateFormat.format(birth);

            String sql = "insert into usr (username,password,birth,create_time)values('"+usr.getUsername()+"','"+usr.getPassword()+"','"+StrBirth+"','"+StrCreateTime+"')";
            System.out.println("sql = " + sql);
            int line = stmt.executeUpdate(sql);
            return  line;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {//释放资源
            JDBCUtil.closeAll(null, stmt, connection);
        }

        return  0;
    }




}
